const jwt = require("jsonwebtoken");

const { USER_SECRET } = require("../config/config.default");
const { tokenExpiredError, invalidToken } = require("../constant/err.type");

const auth = async (ctx, next) => {
  const { authorization } = ctx.request.header;
  try {
    const userData = jwt.verify(
      authorization.replace("Bearer ", ""),
      USER_SECRET
    );
    const { iat, exp, ...data } = userData;
    ctx.state.id = userData.id;
    ctx.response.body = {
      code: "10100",
      message: "用户信息获取成功",
      data,
    };
  } catch (error) {
    console.log("token校验出错", error.name);
    console.log(error);
    if (error) {
      switch (error.name) {
        case "TokenExpiredError":
          ctx.app.emit("error", tokenExpiredError, ctx);
          break;
        case "JsonWebTokenError":
          ctx.app.emit("error", invalidToken, ctx);
          break;
        default:
          ctx.app.emit("error", invalidToken, ctx);
      }
    }
  }
  await next();
};

module.exports = {
  auth,
};
